<template>
    <div v-loading="loading" loading-tip="提测中，请耐心等待...">
        <!-- jira来源的 -->
        <div v-if="detail.jiraId">
            <flexbox justify="flex-end" class="btn-group header-btn" v-if="detail.status === '2' && isPM && isAutoTest !== null">
                <a-button @click="handleNext" v-if="testStatus === 0">提测</a-button>
                <a-button @click="handleNext" v-else-if="testStatus === 3">重新提测</a-button>
                <div v-else>
                    <a-button @click="handleNext(3)" v-if="testStatus != 4 && canUpdateTest"> 更新提测 </a-button>
                </div>
            </flexbox>
        </div>
        <!-- 非jira来源的 -->
        <div v-else>
            <flexbox justify="flex-end" class="btn-group header-btn" v-if="!disabled && isAutoTest !== null">
                <a-button @click="handleNext" v-if="testStatus === 0">{{ isAutoTest ? '提测' : '提交' }}</a-button>
                <a-button @click="handleNext" v-else-if="testStatus === 3">重新提测</a-button>
                <div v-else>
                    <a-button
                        @click="handleNext(3)"
                        v-if="!(stepStatus === 'requireTest' && testStatus === 4) && !(stepStatus === 'productManagerReview') && canUpdateTest"
                    >
                        更新提测
                    </a-button>
                </div>
            </flexbox>
        </div>
        <h-section title="基本信息" collapse style="padding-bottom: 0">
            <common-test ref="commonTestRef" :list="testVersionList" v-bind="$props" />
        </h-section>
        <h-section title="相关测试版本" collapse style="padding-bottom: 0">
            <relate-test-version :list="testVersionList" />
        </h-section>
        <h-section title="测试用例" collapse style="padding-top: 0">
            <relate-test-case :detail="detail" />
        </h-section>
        <AddOptionModal ref="addOptionModalRef" @success="handleOptionSuccess" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import store from '@/store';
import { Checkbox } from 'ant-design-vue';
import { isNotEmpty } from '@/utils/is';
import { message } from 'ant-design-vue';
import { useMessage } from '@/hooks/common/useMessage';
import CommonTest from './components/CommonTest.vue';
import RelateTestCase from './components/RelateTestCase.vue';
import RelateTestVersion from './components/RelateTestVersion.vue';
import AddOptionModal from './components/AddOptionModal.vue';
import { defineComponent, ref, unref, reactive, toRefs, computed, h } from 'vue';
export default defineComponent({
    components: {
        RelateTestCase,
        RelateTestVersion,
        CommonTest,
        Checkbox,
        AddOptionModal
    },
    props: {
        detail: {
            type: Object,
            default: () => ({})
        },
        disabled: { type: Boolean, default: false },
        stepStatus: { type: String, default: '' },
        stage: { type: String, default: '' },
        hasAuth: {
            type: Boolean,
            default: false
        },
        testVersionList: {
            type: Array,
            default: () => []
        }
    },
    emits: ['save', 'success'],
    setup(props, { emit }) {
        const commonTestRef = ref<any>();
        const addOptionModalRef = ref<any>();
        const state = reactive<any>({
            form: {},
            isCancalOA: false,
            loading: false
        });
        const { createConfirm } = useMessage();
        // 是否自动提测
        const isAutoTest = computed(() => {
            return unref(commonTestRef) && unref(commonTestRef).isAutoTest;
        });
        const testStatus = computed(() => {
            return unref(commonTestRef)?.testStatus;
        });
        const isPM = computed(() => {
            return store.getters.userInfo.employeeDTO.isPM;
        });
        // 是否可以更新提测
        const canUpdateTest = computed(() => {
            const res = props.testVersionList.some((item: any) => ['已完成', '已中止'].includes(item.requestStatus) && item.acceptStatus === '待审核');
            console.log('测试版本', props.testVersionList, res);
            return !res;
        });
        const handleSave = async (type: number) => {
            let res: any = true;
            const { id, instanceId } = props.detail;
            let query = {
                id,
                instanceId,
                ...unref(commonTestRef).form,
                autoTest: unref(commonTestRef).isAutoTest
            };
            if (unref(commonTestRef).ruleFormRef) {
                res = await handleValidate();
            }
            // 不自动提测保存走版本暂存接口，自测保存走提测暂存接口
            if (!unref(commonTestRef).isAutoTest) {
                if (type === 4) {
                    type = 1;
                }
                const { id, instanceId, files } = query;
                query = {
                    id,
                    instanceId,
                    files,
                    autoTest: unref(commonTestRef).isAutoTest
                };
            }
            if (res) {
                state.form = {
                    ...query
                };
                emit('save', type);
            }
        };
        // 验证
        const handleValidate = () => {
            return new Promise((res) => {
                unref(unref(commonTestRef).ruleFormRef)
                    .validate()
                    .then(
                        () => {
                            res(true);
                        },
                        () => {
                            res(false);
                        }
                    );
            });
        };
        const handleOptionSuccess = (opinion) => {
            handleSubmitTest(opinion);
        };
        const handleSubmitTest = async (opinion = null) => {
            const res = await unref(unref(commonTestRef).ruleFormRef).validate();
            if (res) {
                state.loading = true;
                let query: any = {
                    ...props.detail,
                    pmpTestInformationDTO: {
                        opinion,
                        ...unref(commonTestRef).form
                    },
                    autoTest: unref(commonTestRef).isAutoTest
                };
                // 如果被提测过了，将id和status放到请求参数中
                if (isNotEmpty(unref(commonTestRef).testInfo)) {
                    const { testStatus, testId } = unref(commonTestRef).testInfo;
                    query = {
                        ...query,
                        testStatus,
                        testId
                    };
                }
                const { success, errorMsg } = await api.productProcessModel.initiateTest(query);
                if (success) {
                    emit('success');
                } else {
                    message.error(errorMsg);
                }
                state.loading = false;
            }
        };
        const handleNext = async (type = 1) => {
            const res = props.testVersionList.some((item: any) => item.acceptStatus === '待审核');
            if (type === 3 && res) {
                createConfirm({
                    title: '已有待审核的提测需求，确定要重复发起吗？',
                    onOk: () => {
                        if (unref(isAutoTest) && [1, 2, 4].includes(unref(testStatus))) {
                            // handleSubmitTest();
                            unref(addOptionModalRef).open();
                        } else {
                            let vDom: any = null;
                            if (unref(isAutoTest)) {
                                vDom = h('div', [
                                    h('span', { style: { fontWeight: 'normal' } }, '你选择了【自动提测】，'),
                                    h('b', '此操作会向测试管理平台发起提测需求，不可逆')
                                ]);
                            } else {
                                vDom = h('div', [
                                    h('span', { style: { fontWeight: 'normal' } }, '你选择了【非自动提测】，'),
                                    h('b', '此操作将需要由产品经理自行完成测试任务，并在后续的测试节点上传测试报告，此操作不可逆')
                                ]);
                            }
                            createConfirm({
                                title: vDom,
                                iconType: 'warning',
                                onOk: () => {
                                    // 如果自动提测
                                    if (unref(isAutoTest)) {
                                        // handleSubmitTest();
                                        unref(addOptionModalRef).open();
                                    }
                                    // 不自动提测
                                    else {
                                        handleSave(1);
                                    }
                                }
                            });
                        }
                    }
                });
            } else {
                if (unref(isAutoTest) && [1, 2, 4].includes(unref(testStatus))) {
                    if (type === 3) {
                        unref(addOptionModalRef).open();
                    } else {
                        handleSubmitTest();
                    }
                } else {
                    let vDom: any = null;
                    if (unref(isAutoTest)) {
                        vDom = h('div', [
                            h('span', { style: { fontWeight: 'normal' } }, '你选择了【自动提测】，'),
                            h('b', '此操作会向测试管理平台发起提测需求，不可逆')
                        ]);
                    } else {
                        vDom = h('div', [
                            h('span', { style: { fontWeight: 'normal' } }, '你选择了【非自动提测】，'),
                            h('b', '此操作将需要由产品经理自行完成测试任务，并在后续的测试节点上传测试报告，此操作不可逆')
                        ]);
                    }
                    createConfirm({
                        title: vDom,
                        iconType: 'warning',
                        onOk: () => {
                            // 如果自动提测
                            if (unref(isAutoTest)) {
                                if (type === 3) {
                                    unref(addOptionModalRef).open();
                                } else {
                                    handleSubmitTest();
                                }
                            }
                            // 不自动提测
                            else {
                                handleSave(1);
                            }
                        }
                    });
                }
            }
        };
        return {
            isPM,
            commonTestRef,
            addOptionModalRef,
            canUpdateTest,
            isAutoTest,
            testStatus,
            ...toRefs(state),
            handleNext,
            handleSubmitTest,
            handleSave,
            handleOptionSuccess
        };
    }
});
</script>

<style scoped>
@import '../RelateProcess/CheckProcess/styles/index.less';
</style>




